import requests
import json
import os
import sys
import argparse
import shutil
from datetime import datetime
import colorama
from colorama import Fore, Back, Style

# 初始化colorama
colorama.init(autoreset=True)

class MailClient:
    def __init__(self, config_path='config.json'):
        # 获取用户目录
        self.user_dir = os.path.expanduser('~')
        self.user_config_path = os.path.join(self.user_dir, '.mail_client_config.json')
        
        # 首次启动时，将配置文件复制到用户目录
        if not os.path.exists(self.user_config_path) and os.path.exists(config_path):
            shutil.copy2(config_path, self.user_config_path)
            print(Fore.GREEN + f"配置文件已复制到用户目录: {self.user_config_path}")
        
        self.config_path = self.user_config_path if os.path.exists(self.user_config_path) else config_path
        self.load_config()
        self.clear_screen()  # 初始化时清屏
    
    def clear_screen(self):
        # 清屏命令，兼容Windows和其他系统
        os.system('cls' if os.name == 'nt' else 'clear')
    
    def load_config(self):
        with open(self.config_path, 'r', encoding='utf-8') as f:
            self.config = json.load(f)
    
    def save_config(self):
        # 保存到用户目录下的配置文件
        with open(self.user_config_path, 'w', encoding='utf-8') as f:
            json.dump(self.config, f, ensure_ascii=False, indent=2)
        print(Fore.GREEN + f"配置已保存到用户目录: {self.user_config_path}")
    
    def get_mail_by_id(self, mail_id):
        url = f"{self.config['server_url']}/inbox/{self.config['user']}"
        try:
            response = requests.get(url)
            if response.status_code == 200:
                mails = response.json().get('mails', [])
                for mail in mails:
                    if mail['id'] == mail_id:
                        return mail
        except Exception:
            pass
        return None
    
    def show_mail(self, mail_id):
        self.clear_screen()
        mail = self.get_mail_by_id(mail_id)
        if mail:
            # 打印邮件详情，使用颜色和边框
            print(Fore.CYAN + "=" * 60)
            print(Fore.CYAN + f"           新邮件~          ")
            print(Fore.CYAN + "=" * 60)
            print(Fore.WHITE + f"  时间: {mail['timestamp']}")
            print(Fore.WHITE + f"  主题: {mail['subject']}")
            print(Fore.CYAN + "-" * 60)
            print(Fore.WHITE + f"  内容: {mail['content']}")
            print(Fore.CYAN + "-" * 60)
            if mail['attachments']:
                print(Fore.MAGENTA + f"  附件: {len(mail['attachments'])} 个")
            else:
                print(Fore.MAGENTA + "  附件: 无")
            print(Fore.CYAN + "=" * 60)
            self.mark_as_read(mail_id)
        else:
            print(Fore.RED + "未找到指定邮件")
    
    def send_mail(self, subject, content, attachment_path=None):
        url = f"{self.config['server_url']}/send"
        data = {
            'sender': self.config['user'],
            'subject': subject,
            'content': content
        }
        
        files = {}
        if attachment_path and os.path.exists(attachment_path):
            files['attachment'] = open(attachment_path, 'rb')
        
        try:
            response = requests.post(url, data=data, files=files)
            if files:
                files['attachment'].close()
            return response.json()
        except Exception as e:
            if files:
                files['attachment'].close()
            return {'status': 'error', 'message': str(e)}
    
    def get_inbox(self, unread_only=False):
        url = f"{self.config['server_url']}/inbox/{self.config['user']}"
        params = {'unread_only': str(unread_only).lower()}
        try:
            response = requests.get(url, params=params)
            return response.json()
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    def mark_as_read(self, mail_id):
        url = f"{self.config['server_url']}/mark_as_read/{mail_id}"
        try:
            response = requests.post(url)
            return response.json()
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    def get_attachment(self, attachment_id, save_path):
        url = f"{self.config['server_url']}/attachment/{attachment_id}"
        try:
            response = requests.get(url)
            if response.status_code == 200:
                with open(save_path, 'wb') as f:
                    f.write(response.content)
                return {'status': 'success', 'message': f'附件已保存到 {save_path}'}
            else:
                return {'status': 'error', 'message': '下载附件失败'}
        except Exception as e:
            return {'status': 'error', 'message': str(e)}
    
    def show_unread_mails(self):
        self.clear_screen()
        result = self.get_inbox(unread_only=True)
        if result['status'] == 'success':
            mails = result['mails']
            if not mails:
                print(Fore.GREEN + "没有未读邮件")
                input("\n按Enter键返回...")
                return
            
            print(Fore.CYAN + "=" * 60)
            print(Fore.CYAN + f"           未读的邮件~           ")
            print(Fore.CYAN + "=" * 60)
            for i, mail in enumerate(mails):
                print(Fore.WHITE + f"{i+1}. 来自 对方 的邮件")
                print(Fore.WHITE + f"   主题: {mail['subject']}")
                content_preview = mail['content'][:50] + ('...' if len(mail['content']) > 50 else '')
                print(Fore.WHITE + f"   内容: {content_preview}")
                print(Fore.WHITE + f"   时间: {mail['timestamp']}")
                if mail['attachments']:
                    print(Fore.MAGENTA + f"   附件: {len(mail['attachments'])} 个")
                print(Fore.CYAN + "-" * 60)
        else:
            print(Fore.RED + f"获取未读邮件失败: {result['message']}")
        input("\n按Enter键返回...")
    
    def show_all_mails(self):
        self.clear_screen()
        result = self.get_inbox()
        if result['status'] == 'success':
            mails = result['mails']
            if not mails:
                print(Fore.GREEN + "收件箱为空")
                input("\n按Enter键返回...")
                return
            
            print(Fore.CYAN + "=" * 60)
            print(Fore.CYAN + f"           收件箱列表~           ")
            print(Fore.CYAN + "=" * 60)
            for i, mail in enumerate(mails):
                status = Fore.GREEN + "已读" if mail['read'] else Fore.RED + "未读"
                print(Fore.WHITE + f"{i+1}. [{status}] 来自 对方 的邮件")
                print(Fore.WHITE + f"   主题: {mail['subject']}")
                content_preview = mail['content'][:50] + ('...' if len(mail['content']) > 50 else '')
                print(Fore.WHITE + f"   内容: {content_preview}")
                print(Fore.WHITE + f"   时间: {mail['timestamp']}")
                if mail['attachments']:
                    print(Fore.MAGENTA + f"   附件: {len(mail['attachments'])} 个")
                print(Fore.CYAN + "-" * 60)
        else:
            print(Fore.RED + f"获取收件箱失败: {result['message']}")
        input("\n按Enter键返回...")
    
    def modify_config(self):
        self.clear_screen()
        print(Fore.CYAN + "=" * 60)
        print(Fore.CYAN + f"           当前配置           ")
        print(Fore.CYAN + "=" * 60)
        for key, value in self.config.items():
            print(Fore.WHITE + f"  {key}: {value}")
        
        print(Fore.CYAN + "=" * 60)
        print(Fore.CYAN + f"         修改配置         ")
        print(Fore.CYAN + "=" * 60)
        print(Fore.WHITE + "请输入新的配置值 (直接回车保持不变)")
        
        server_url = input(Fore.WHITE + f"服务器地址 [{self.config['server_url']}]: ").strip()
        if server_url:
            self.config['server_url'] = server_url
        
        user = input(Fore.WHITE + f"用户名 [{self.config['user']}]: ").strip()
        if user:
            self.config['user'] = user
        
        check_interval = input(Fore.WHITE + f"检查间隔(秒) [{self.config['check_interval']}]: ").strip()
        if check_interval:
            try:
                self.config['check_interval'] = int(check_interval)
            except ValueError:
                print(Fore.RED + "检查间隔必须是数字，保持原值不变")
        
        self.save_config()
        print(Fore.GREEN + "配置已更新")
        input("\n按Enter键返回...")
    
    def show_menu(self):
        self.clear_screen()
        print(Fore.CYAN + "=" * 60)
        print(Fore.CYAN + f"        OUR邮件客户端        ")
        print(Fore.CYAN + "=" * 60)
        print(Fore.WHITE + "1. 发送邮件")
        print(Fore.WHITE + "2. 查看未读~")
        print(Fore.WHITE + "3. 查看收件箱")
        print(Fore.WHITE + "4. 修改配置")
        print(Fore.WHITE + "5. 退出")
        print(Fore.CYAN + "=" * 60)
    
    def run(self):
        while True:
            self.show_menu()
            choice = input(Fore.WHITE + "请选择操作: ").strip()
            
            if choice == '1':
                self.clear_screen()
                print(Fore.CYAN + "=" * 60)
                print(Fore.CYAN + f"         发送邮件         ")
                print(Fore.CYAN + "=" * 60)
                subject = input(Fore.WHITE + "邮件主题: ").strip()
                content = input(Fore.WHITE + "邮件内容: ").strip()
                attachment = input(Fore.WHITE + "附件路径 (可选): ").strip()
                if not attachment:
                    attachment = None
                
                result = self.send_mail(subject, content, attachment)
                if result['status'] == 'success':
                    print(Fore.GREEN + f"邮件发送成功，ID: {result['mail_id']}")
                else:
                    print(Fore.RED + f"邮件发送失败: {result['message']}")
                input("\n按Enter键返回...")
            
            elif choice == '2':
                self.show_unread_mails()
            
            elif choice == '3':
                self.show_all_mails()
            
            elif choice == '4':
                self.modify_config()
            
            elif choice == '5':
                print(Fore.GREEN + "拜拜~~")
                sys.exit(0)
            
            else:
                print(Fore.RED + "嗯？我没有这个选项")
                input("按Enter键继续...")

# 处理命令行参数
def main():
    parser = argparse.ArgumentParser(description='邮件客户端')
    parser.add_argument('--show-mail', type=str, help='显示指定ID的邮件')
    args = parser.parse_args()
    
    client = MailClient()
    if args.show_mail:
        client.show_mail(args.show_mail)
    else:
        client.run()

if __name__ == '__main__':
    main()